package com.liao.tensquare.admin.controller;

import com.liao.tensquare.annotation.Log;
import com.liao.tensquare.constants.TokenConstants;
import com.liao.tensquare.entity.Result;
import com.liao.tensquare.entity.StatusCode;
import com.liao.tensquare.admin.pojo.TbUser;
import com.liao.tensquare.admin.service.TbUserService;
import com.liao.tensquare.enums.OperatorType;
import com.liao.tensquare.utils.AsyncUtil;
import com.liao.tensquare.utils.StringHelper;
import com.liao.tensquare.admin.vo.UserInfoResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.UUID;

@Slf4j
@RequestMapping("file")
@RestController
public class FileController {

    @Autowired
    private TbUserService userService;

    @Autowired
    private AsyncUtil asyncUtil;

    @Log(value = "上传头像",isSave = true,operType = OperatorType.EXPORT)
    @RequestMapping(value = "/upLoad/avatar", method = RequestMethod.POST)
    public Result upLoadUserAvatar(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) {
        if (multipartFile.getSize() > 1024 * 1024 * 2) {
            return new Result(false, "上传的最大文件为2M", StatusCode.PARAMS_IN_ERROR);
        }
        String filename = multipartFile.getOriginalFilename();
        if (filename == null) {
            return new Result(false, "文件名为空", StatusCode.PARAMS_IN_ERROR);
        }
//        String path = "http://localhost:8080/tensquare/user/avatar/";

        //获取文件后缀名
        String substring = filename.substring(filename.lastIndexOf("."));
        URL resource = this.getClass().getClassLoader().getResource("static");
        if (resource == null) {
            return new Result(false, "服务器异常", StatusCode.ERROR);
        }
        //获取资源文件的位置
        String path = resource.getPath();
        //拼接用户头像的地址
        filename = path + "/avatars/";
        File fileDirectory = new File(filename);
        String imgName = UUID.randomUUID() + substring;
        //用户头像的文件名称
        String newFileName = filename + imgName;
        //用户头像
        File destFile = new File(newFileName);
        try {
            if (!fileDirectory.exists()) {
                if (!fileDirectory.mkdir()) {
                    return new Result(false, "文件夹创建失败", StatusCode.ERROR);
                }
            }
            //保存用户头像
            multipartFile.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(true, "上传失败", StatusCode.ERROR);
        }
        String userId = (String) request.getAttribute(TokenConstants.JWT_USER_ID);
        UserInfoResponse userInfo = userService.findUserById(userId);
        String oldAvatar = userInfo.getAvatar();
        if (!StringHelper.isEmpty(oldAvatar)) {
            asyncUtil.delAvatarImg(path + oldAvatar);
        }
        TbUser tbUser = new TbUser();
        tbUser.setId(userId);
        String avatarPath = "/avatars/" + imgName;
        tbUser.setAvatar(avatarPath);
        userService.updateUser(tbUser);
        return new Result(true, "上传成功", StatusCode.OK,avatarPath);
    }

}
